import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
	  //商品列表数据
	  shoplist:[
		  {'id':1,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife.jpg'},
		  {'id':2,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife(2).jpeg'},
		  {'id':3,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife.jpg'},
		  {'id':4,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife(2).jpeg'},
		  {'id':5,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife.jpg'},
		  {'id':6,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife(2).jpeg'},
		  {'id':7,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife.jpg'},
		  {'id':8,'title':'樱岛麻衣','price':999.9, src:'/images/cjn_wife(2).jpeg'},
		
	  ],
	  
	  //购物车列表数据
	  shopcart:[]
	  
  },
  //getters可以对state里面的数据进行简单的计算或者过滤
  getters: {
	  //计算总价
	  totalprice(state){
		  return state.shopcart.reduce(function(total,item){
			  return total += item.price * item.num;
		  },0)
	  }
  },
  mutations: {
	  //添加购物车
	  add(state,item){	//mutations会接收state作为第一个参数
		//查找shopcart里面是否已有添加这个商品
		  var first = state.shopcart.find(i => i.id == item.id)
		  if(first){
			  first.num++
		  }else{
			  state.shopcart.push({
				  id:item.id,
				  title:item.title,
				  price:item.price,
				  scr:item.src,
				  num:1
			  })
		  }
	  },
	  
	  
	  
	  //删除购物车
	  del(state,item){	//mutations会接收state作为第一个参数
	  		state.shopcart.forEach(function(i,index,arr){
				if(i.id == item.id){
					arr.splice(index,1);
				}
			})
	  }
  },
  actions: {
  },
  modules: {
  }
})
